package com.mlk.rbac.Service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.mlk.core.constants.Constant;
import com.mlk.core.util.ServerResponse;
import com.mlk.core.util.SessionUtils;
import com.mlk.rbac.Service.SysRoleAclService;
import com.mlk.rbac.mapper.SysAclModuleMapper;
import com.mlk.rbac.mapper.SysRoleAclMapper;
import com.mlk.rbac.po.SysAclModule;
import com.mlk.rbac.po.SysRoleAcl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;


/**
 * 角色权限服务
 * @author trekxu
 */
@Service
public class SysRoleAclServiceImpl implements SysRoleAclService {
	
	@Resource
	private SysRoleAclMapper sysRoleAclMapper;
	
	@Resource
	private SysAclModuleMapper sysAclModuleMapper;

	@Override
	public ServerResponse roleAcl(Integer id) {
		if(id == null) {
			return ServerResponse.fail("角色的id不能为空");
		}
		
		// 查询所有的可用权限内容
		List<SysAclModule> acls = this.sysAclModuleMapper.selectList(new EntityWrapper<>(SysAclModule.builder().status(Constant.status_ok).build()));
		
		// 查询当前角色的可用权限
		List<SysRoleAcl> roleAcls = this.sysRoleAclMapper.selectList(new EntityWrapper<>(SysRoleAcl.builder().roleId(id).build()));
		Integer[] checkedId = adaptRoleAcls(roleAcls);
		Map<String,Object> result = Maps.newHashMap();
		result.put("list", acls);
		result.put("checkedId", checkedId);
		return ServerResponse.ok(result);
	}
	
	/**
	 * 映射id列表id列表
	 * @param roleAcls
	 * @return
	 */
	private Integer[] adaptRoleAcls(List<SysRoleAcl> roleAcls) {
		 Integer[] result = new Integer[roleAcls.size()];
		 roleAcls.stream().map(e-> e.getAclId()).collect(Collectors.toList()).toArray(result);
		 return result;
	}
	
	@Override
	@Transactional
	public ServerResponse allocate(Integer roleId, String[] aclIds) {
		if(roleId == null) {
			return ServerResponse.fail("分配角色的id不能为空");
		}
		
		// 将数据转换
		List<SysRoleAcl> roleAcls = converterAcls(roleId,aclIds);
		
		// 首先删除之前的分配关系
		this.sysRoleAclMapper.delete(new EntityWrapper<>(SysRoleAcl.builder().roleId(roleId).build()));
		//然后批量添加数据
		if(!roleAcls.isEmpty()) {
			int count = this.sysRoleAclMapper.insertBatch(roleAcls);
			
			if(count != roleAcls.size() ) {
				return ServerResponse.fail("分配权限出现问题");
			}
		}
		
		return ServerResponse.ok("分配权限成功");
	}
	
	
	private List<SysRoleAcl> converterAcls(Integer roleId, String[] aclIds) {
		List<SysRoleAcl>  result = Lists.newArrayList();
		for(String aclId : aclIds) {
			SysRoleAcl model = SysRoleAcl.builder().aclId(Integer.parseInt(aclId)).roleId(roleId).operateTime(new Date()).operator(SessionUtils.getSysUser().getName()).build();
			result.add(model) ;
		}
		return result;
	}
	
	
}
